﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

using CloudSoft.Workflows;
using ERPStore.NewsLetters.Repositories;

namespace ERPStore.NewsLetters.Workflows.Activities
{
	public sealed class WriteTrackLog : CodeActivity
	{
		public InArgument<Models.TrackingKey> TrackingKey { get; set; }
		public InArgument<string> RawUrl { get; set; }
		public InArgument<string> IP { get; set; }
		public InArgument<string> DestinationUrl { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			var trackRepository = context.GetService<Services.TrackerService>();
			var newsLetterService = context.GetService<Services.NewsLettersService>();
			var logger = context.GetService<ERPStore.Logging.ILogger>();
			var bus = context.GetService<ERPStore.Services.IServiceBus>();

			var trackingKey = context.GetValue(this.TrackingKey);
			var rawUrl = context.GetValue(this.RawUrl);
			var ip = context.GetValue(this.IP);
			var destinationUrl = context.GetValue(DestinationUrl);
			var emailSentResult = newsLetterService.GetLastEmailSent(trackingKey);

			var creationDate = DateTime.Now;
			int? emailSentId = null;
			if (emailSentResult != null)
			{
				creationDate = emailSentResult.SentDate;
				emailSentId = emailSentResult.Id;
			}
			trackRepository.WriteTrack(trackingKey, creationDate, rawUrl, ip, destinationUrl, emailSentId);
		}

	}
}
